﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using XTeam.Document.Entities.Words;
using XTeam.Document.Factory.ServiceInterface;
using Spring.Context;
using Spring.Context.Support;

namespace XTeam.Document.Controllers.Manage
{
    public class WordsController : BasicController
    {
        private IWordsService _wordsService;

        public WordsController()
        {
            IApplicationContext _context = ContextRegistry.GetContext();
            _wordsService = (IWordsService)_context.GetObject("WordsService");
        }


        public ActionResult WordPost(string word = "")
        {
            var entry = _wordsService.FindWord(word);
            // entry = entry ?? new WordsEntity();
            return View(entry);
        }

        [HttpPost]
        public ActionResult WordPost(WordsEntity entry, int a = 0)
        {
            WordsEntity oldEntity = null;
            if (entry != null)
            {
                oldEntity = _wordsService.FindWord(entry.Word);
            }
            if (oldEntity != null)
            {
                _wordsService.UpdateWord(entry);
            }
            else
            {
                _wordsService.AppendWord(entry);
            }

            return View();
        }

        public ActionResult List(int p = 0, string key = "")
        {
            int totalRows = 0;
            int pageSize = 10;
            key = key.Trim().ToUpper();
            IList<WordsEntity> resultTable = _wordsService.Search(i => i.Word.ToUpper().Contains(key), p, pageSize, out totalRows);
            string hrefFormat = Url.Action(string.Format("{0}", RouteData.Values["Action"]), new { p = "{0}", key = key });
            ViewBag.Pager = this.CreatePager(hrefFormat, p, pageSize, totalRows);
            return View(resultTable);
        }

        [HttpPost]
        public ActionResult DelWords(string[] words, string word = "")
        {
            if (words != null && words.Length > 0)
            {
                _wordsService.DelWords(words);
            }

            return new EmptyResult();
        }

        public ActionResult AutoComplete(string q = "")
        {
            int totalRows = 0;
            int pageSize = 10;
            q = q.Trim().ToUpper();
            IList<WordsEntity> resultTable = _wordsService.Search(i => i.Word.ToUpper().IndexOf(q) == 0 && !string.IsNullOrEmpty(q), 0, pageSize, out totalRows);

            return Json(resultTable, JsonRequestBehavior.AllowGet);
        }
    }
}
